package com.eln.medplayer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.media.AudioManager;

public class VidActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
	private static final String TAG = "VideoPlayer";
	
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnHome;
	private ImageButton btnSound;
	private SeekBar videoProgressBar;
	private TextView videoTitleLabel;
	private TextView videoCurrentDurationLabel;
	private TextView videoTotalDurationLabel;
	// Media Player
	//private  MediaPlayer mp;
		// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
		//private SongsManager songManager;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	//private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();

	private VideoView mVideoView;
	private String current;
	private static Animation slideUpIn;
	private static Animation slideUpOut;
	private static Animation slideTopIn;
	private static Animation slideTopOut;
	private static View controlsView;
	private static View titleView;
	private static View mainView;
	private static View progressView;
	static RelativeLayout progressLayout;
	private static int currentVideoIndex=0;
	private static int menuOption=0;
	private static int soundPos=0;
	private static int soundPosMax=0;
	private static int sp=0;
	private static ArrayList<Movie> movieList;
	private static  AudioManager mAudioManager;
	//MediaHelper mh=null;
	//private List<String> videolist;
	//private static final String MEDIA_VIDEO_PATH = new String("/mnt/sdcard/video");
	
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private GestureDetector gestureDetector;
    private GestureDetector gestureDetectorSound;
    protected MyGestureListener myGestureListener;
    public static float startX=0;
    float currX=0;
    public static float X0=0;
    public static float XMax=0;


	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    setVolumeControlStream(AudioManager.STREAM_MUSIC);
	    
	    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
	    soundPos = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	    soundPosMax=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);   
	    
	    RelativeLayout relative = new RelativeLayout(this);
	    
	    mainView=View.inflate(getBaseContext(),R.layout.video_player,null);
	    relative.addView(mainView);
	    
	    controlsView=View.inflate(getBaseContext(),R.layout.controls_vid,null);
        relative.addView(controlsView);
        controlsView.setVisibility(View.GONE);
        
        titleView=View.inflate(getBaseContext(),R.layout.title_vid,null);
        relative.addView(titleView);
        titleView.setVisibility(View.GONE);
        
        progressView = View.inflate(getBaseContext(),R.layout.progressbar, null);
        relative.addView(progressView);
		
       // setContentView(R.layout.video_player);
	    setContentView(relative);
	    
	    gestureDetector = new GestureDetector(new MyGestureDetector());
	    gestureDetectorSound = new GestureDetector(new MyGestureDetectorSound());
	    
	    progressLayout = (RelativeLayout) findViewById(R.id.progressLayout);
		progressLayout.setVisibility(View.VISIBLE);
	    
	    //controlsView.setVisibility(View.GONE);
		//titleView.setVisibility(View.GONE);"
	    
	    Intent i = getIntent();
	    currentVideoIndex = i.getExtras().getInt("listIndex");
	    menuOption = i.getExtras().getInt("menuOption");
	   // movieList=(ArrayList<Movie>)i.getExtras().getSerializable("movieList");
	    movieList=i.getParcelableArrayListExtra("movieList"); 
	    
		mVideoView = (VideoView) findViewById(R.id.surface_view);
		
		/*mVideoView.setOnTouchListener(new View.OnTouchListener() {
	            public boolean onTouch(View v, MotionEvent event) {
	            	if (controlsView.getVisibility()==View.GONE){
	                if (gestureDetector.onTouchEvent(event)) {
	                    return true;
	                }
	            	}
	                return false;
	            }
	        });*/
		
		myGestureListener = new MyGestureListener(this);
		
		mVideoView.setOnTouchListener(myGestureListener);
		
		 
		
		
		// All player buttons
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnPlay.setImageResource(R.drawable.btn_pause);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
		btnHome = (ImageButton) findViewById(R.id.btnHome);
		btnSound = (ImageButton) findViewById(R.id.btnSound);
		videoProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		videoTitleLabel = (TextView) findViewById(R.id.songTitle);
		videoCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		videoTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
		
		setVolumeCtrl(getBaseContext(),btnSound,soundPos);
		// Listeners
		videoProgressBar.setOnSeekBarChangeListener(this); // Important
		mVideoView.setOnCompletionListener(this); // Important
		
		utils = new Utilities();
		
	    slideUpIn = AnimationUtils.loadAnimation(this, R.anim.slide_up);
        slideUpOut = AnimationUtils.loadAnimation(this, R.anim.slide_down);
        
        slideTopIn = AnimationUtils.loadAnimation(this, R.anim.slide_top_down);
        slideTopOut = AnimationUtils.loadAnimation(this, R.anim.slide_top_up);
		//mh=new MediaHelper();
		//mh.getVideoList();
        
		//File vidpath = new File(MEDIA_VIDEO_PATH);
		//videolist= new ArrayList<String>();
		//videolist=Arrays.asList(vidpath.list());//mh.videols;
		
	/*	mPlay.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				playVideo(videolist.get(0));
			}
		});
		mPause.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if (mVideoView != null) {
					mVideoView.pause();
				}
			}
		});
		mReset.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if (mVideoView != null) {
					mVideoView.seekTo(0);
				}
			}
		});
		mStop.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				if (mVideoView != null) {
					current = null;
					mVideoView.stopPlayback();
				}
			}
		});*/
		
		 btnPlay.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					
					// check for already playing
					if(mVideoView.isPlaying()){
						if(mVideoView!=null){
							mVideoView.pause();
							// Changing button image to play button
							btnPlay.setImageResource(R.drawable.btn_play);
						}
					}else{
						// Resume song
						if(mVideoView!=null){
							mVideoView.start();
							// Changing button image to pause button
							btnPlay.setImageResource(R.drawable.btn_pause);
						}
					}
					
				}
			});
			
			
			/**
			 * Next button click event
			 * Plays next song by taking currentSongIndex + 1
			 * */
			btnNext.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// check if next song is there or not
					if(currentVideoIndex < (movieList.size() - 1)){
						playVideo(currentVideoIndex + 1);
						currentVideoIndex = currentVideoIndex + 1;
					}else{
						// play first song
						playVideo(0);
						currentVideoIndex = 0;
					}
					
				}
			});
			
			/**
			 * Back button click event
			 * Plays previous song by currentSongIndex - 1
			 * */
			btnPrevious.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(currentVideoIndex > 0){
						playVideo(currentVideoIndex - 1);
						currentVideoIndex = currentVideoIndex - 1;
					}else{
						// play last song
						playVideo(movieList.size() - 1);
						currentVideoIndex = movieList.size() - 1;
					}
					
				}
			});
			
				
			/**
			 * Button Click event for Play list click event
			 * Launches list activity which displays list of songs
			 * */
			btnPlaylist.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					mHandler.removeCallbacks(mUpdateTimeTask);
					Intent i = new Intent(getApplicationContext(), VidList.class);
					i.putExtra("menuOption",menuOption);
					startActivity(i);
					VidActivity.this.overridePendingTransition(
							R.anim.slide_in_left, 
							R.anim.slide_out_right
				    		);
					finish();
				}
			});
			
            btnHome.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					mHandler.removeCallbacks(mUpdateTimeTask);
					Intent i = new Intent(getApplicationContext(), MedPlayer.class);
					i.putExtra("menuOption",menuOption);
					startActivity(i);
					finish();
				}
			});
            
          /*  btnSound.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
				   if (soundPos+sp>soundPosMax){
				     sp=sp*-1;
				   }
				   if (soundPos+sp<0){
					 sp=sp*-1;  
				   }
				   setVolumeCtrl(getBaseContext(),btnSound);
				   soundPos=soundPos+sp;
				   mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, soundPos+sp, 0);
				}
            });*/
            
           btnSound.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // TODO Auto-generated method stub
                	if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
                		event.getX();
                        return true;
                    } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                       startX=event.getX();
                       X0=btnSound.getX();
                       XMax=btnSound.getX()+btnSound.getWidth();
                        return true;
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    	//int pos=Math.round((currX-startX)*soundPosMax/150);
	                      
	                       
	                      // setVolumeCtrl(getBaseContext(),btnSound);
	                      // int reaalPos=Math.round(soundPos);
	                       //if (reaalPos==1) {reaalPos=0;}
	                       //if (reaalPos==11) {reaalPos=soundPosMax;}
	                       //mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, reaalPos, 0);
                        return true;
                    } else if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
                    {

                        // Do some stuffs here
                    }
                    else if(event.getAction()==MotionEvent.ACTION_MOVE)
                    {
                        currX=event.getX();
	                       float step=Math.round(currX-startX);
	                       int pos=Math.round((startX+step)*soundPosMax/XMax);
	                       setVolumeCtrl(getBaseContext(),btnSound,pos);
                           mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, pos, 0);
                    }

                    return false;
                }
            }); 
            
                  
          /*  btnSound.setOnTouchListener(new View.OnTouchListener() {
	            public boolean onTouch(View v, MotionEvent event) {
	            	if (gestureDetectorSound.onTouchEvent(event)) {
	                    return true;
	                }
	                return false;
	            }
	        });*/
            
            
        /*    SeekBar volControl = (SeekBar)findViewById(R.id.volumeProgressBar);
            volControl.setMax(soundPosMax);
            volControl.setProgress(soundPos);
            volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {
         // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
         // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
         // TODO Auto-generated method stub
        	setVolumeCtrl(getBaseContext(),btnSound,arg1);
        	mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
        }
       });*/
            
            thread.start();
		
	//	runOnUiThread(new Runnable(){
	//		public void run() {
	//				playVideo(videolist.get(currentVideoIndex));
				
	//			progressLayout.setVisibility(View.INVISIBLE); 
	//		}
			
	//	});
		
		
	}
	
	 public static void setVolumeCtrl(Context ctx,ImageButton bt,int pos){
		   soundPos = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		   int ps=Math.round(11*pos/soundPosMax)+1;
		   if (ps>11) {ps=11;} 
           if (ps<1) {ps=1;}
     	   int resId = ctx.getResources().getIdentifier("loudness_"+ps, "drawable", ctx.getPackageName());
		   bt.setImageResource(resId);
	   }
	
	
	Thread thread = new Thread()
	{
	    @Override
	    public void run() {
	    	//try {
			//	sleep(2000);
			//} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			//	e.printStackTrace();
			//}
	    	playVideoPath(movieList.get(currentVideoIndex).getMoviePath(),movieList.get(currentVideoIndex).getTitle());
			
			progressLayout.setVisibility(View.INVISIBLE);
	    }
	};
	
	public static void callMenu(){
		if (controlsView.getVisibility()==View.VISIBLE){
			controlsView.startAnimation(slideUpOut);
			controlsView.setVisibility(View.GONE);
			titleView.startAnimation(slideTopOut);
			titleView.setVisibility(View.GONE);
		}else{
			controlsView.startAnimation(slideUpIn);
			controlsView.setVisibility(View.VISIBLE);
			titleView.startAnimation(slideTopIn);
			titleView.setVisibility(View.VISIBLE);
		}
	}

	
	private void playVideo(int index) {
		String path=movieList.get(index).getMoviePath();
		String title=movieList.get(index).getTitle();
		playVideoPath(path,title);
	}
	
	private void playVideoPath(String path,String title) {
		try {
			Log.v(TAG, "path: " + path);
			//path = MEDIA_VIDEO_PATH+"/"+path;
			if (path == null || path.length() == 0) {
				Toast.makeText(VidActivity.this, "File URL/path is empty",
						Toast.LENGTH_LONG).show();

			} else {
				// If the path has not changed, just start the media player
				if (path.equals(current) && mVideoView != null) {
					mVideoView.start();
					mVideoView.requestFocus();
					return;
				}
				current = path;
				mVideoView.setVideoPath(getDataSource(path));
				mVideoView.start();
				mVideoView.requestFocus();

			}
			//String songTitle = path;
			File fl=new File(path);
        	videoTitleLabel.setText(title);//clearedFilename(fl.getName()));
			
			videoProgressBar.setProgress(0);
			videoProgressBar.setMax(100);
			
			// Updating progress bar
			updateProgressBar();			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
			
		//} catch (Exception e) {
		//	Log.e(TAG, "error: " + e.getMessage(), e);
		//	if (mVideoView != null) {
		//		mVideoView.stopPlayback();
		//	}
		//}
	}
	

	private String getDataSource(String path) throws IOException {
		if (!URLUtil.isNetworkUrl(path)) {
			return path;
		} else {
			URL url = new URL(path);
			URLConnection cn = url.openConnection();
			cn.connect();
			InputStream stream = cn.getInputStream();
			if (stream == null)
				throw new RuntimeException("stream is null");
			File temp = File.createTempFile("mediaplayertmp", "dat");
			temp.deleteOnExit();
			String tempPath = temp.getAbsolutePath();
			FileOutputStream out = new FileOutputStream(temp);
			byte buf[] = new byte[128];
			do {
				int numread = stream.read(buf);
				if (numread <= 0)
					break;
				out.write(buf, 0, numread);
			} while (true);
			try {
				stream.close();
			} catch (IOException ex) {
				Log.e(TAG, "error: " + ex.getMessage(), ex);
			}
			return tempPath;
		}
	}
	
	/*@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 currentVideoIndex = data.getExtras().getInt("videoIndex");
         	 // play selected song
             playVideo(currentVideoIndex);
        }
 
    }*/
	
/*	@Override
    public boolean onTouchEvent(MotionEvent event) {

		   final int action = event.getAction();
                float y=event.getY();
        		   if((action == MotionEvent.ACTION_UP) && (y<650) && (controlsView.getVisibility()==View.VISIBLE)) {
        		       callMenu();
        		   }else  if((action == MotionEvent.ACTION_UP )&&(controlsView.getVisibility()==View.GONE)) 
        			   { callMenu();}
		   return super.onTouchEvent(event);
    }*/
	
	@Override
    public boolean onTouchEvent(MotionEvent event) {
        // or implement in activity or component. When your not assigning to a child component.
		final int action = event.getAction();
        float y=event.getY();
		   if((action == MotionEvent.ACTION_UP) && (y<550) && (controlsView.getVisibility()==View.VISIBLE)) {
		       callMenu();
		   }else  if((action == MotionEvent.ACTION_UP )&&(controlsView.getVisibility()==View.GONE)) 
			   { callMenu();}
        return myGestureListener.getDetector().onTouchEvent(event); 
    }
	
	
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);        
    }	
	
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mVideoView.getDuration();
			   long currentDuration = mVideoView.getCurrentPosition();
			  
			   // Displaying Total Duration time
			   videoTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   videoCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)+" /");
			   
			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			  videoProgressBar.setProgress(progress);
			   
			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};
		
	/**
	 * 
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		
	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }
	
	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mVideoView.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
		
		// forward or backward to certain seconds
		mVideoView.seekTo(currentPosition);
		
		// update timer progress again
		updateProgressBar();
    }

	/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {
		
		    progressLayout.setVisibility(View.VISIBLE);  
			// no repeat or shuffle ON - play next song
			if(currentVideoIndex < (movieList.size() - 1)){
				//playVideo(currentVideoIndex + 1);
				//currentVideoIndex = currentVideoIndex + 1;
			}else{
				// play first song
				//playVideo(0);
				//currentVideoIndex = 0;
			}
			progressLayout.setVisibility(View.INVISIBLE);  
	}
	
	@Override
	public void onBackPressed() {
		mHandler.removeCallbacks(mUpdateTimeTask);
		Intent i = new Intent(getApplicationContext(), VidList.class);
		i.putExtra("menuOption",menuOption);
		startActivity(i);
		VidActivity.this.overridePendingTransition(
				R.anim.slide_in_left, 
				R.anim.slide_out_right
	    		);
		finish();
	}
	
	@Override
	 public void onDestroy(){
	 super.onDestroy();
	 }
	
    public String clearedFilename(String filename){
    	String res=filename;
        int pos = res.lastIndexOf(".");
        if (pos > -1) res=res.substring(0, pos);
        res=res.replace("_LT","");
        res=res.replace("_EN","");
        pos = res.lastIndexOf("_");
        if (pos > -1) res=res.substring(pos+1, res.length());
    	return res;
    }
    
    class MyGestureDetector extends SimpleOnGestureListener {
    	
    	
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	    
        	Intent intent = new Intent(VidActivity.this.getBaseContext(), VidActivity.class);
	    
	    intent.putExtra("menuOption", menuOption);
        intent.putParcelableArrayListExtra("movieList",movieList);
 
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
 
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	if(currentVideoIndex < (movieList.size() - 1)){
					currentVideoIndex = currentVideoIndex + 1;
				}else{
					currentVideoIndex = 0;
				}
            intent.putExtra("listIndex", currentVideoIndex);
    		startActivity(intent);
    		VidActivity.this.overridePendingTransition(
			R.anim.slide_in_right,
			R.anim.slide_out_left
    		);
    		finish();
    	    // right to left swipe
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	if(currentVideoIndex > 0){
            		currentVideoIndex = currentVideoIndex - 1;
				}else{
					currentVideoIndex = movieList.size() - 1;
				}
            intent.putExtra("listIndex", currentVideoIndex);
    		startActivity(intent);
    		VidActivity.this.overridePendingTransition(
			R.anim.slide_in_left, 
			R.anim.slide_out_right
    		);
    		finish();
            }
 
            return false;
        }
        
       
 
        // It is necessary to return true from onDown for the onFling event to register
        @Override
        public boolean onDown(MotionEvent e) {
	        	return true;
        }
    }
    
    class MyGestureDetectorSound extends SimpleOnGestureListener {
    	
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
 
        	
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                return false;
            }
 
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
           
    		
    	    // right to left swipe
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	
    
    		
            }
 
            return false;
        }
 
        // It is necessary to return true from onDown for the onFling event to register
        @Override
        public boolean onDown(MotionEvent e) {
	        	return true;
        }
    }
    
    class MyGestureListener extends SimpleOnGestureListener implements OnTouchListener
    {
        Context context;
        GestureDetector gDetector;

        public MyGestureListener()
        {
            super();
        }

        public MyGestureListener(Context context) {
            this(context, null);
        }

        public MyGestureListener(Context context, GestureDetector gDetector) {

            if(gDetector == null)
                gDetector = new GestureDetector(context, this);

            this.context = context;
            this.gDetector = gDetector;
        }


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        	Intent intent = new Intent(VidActivity.this.getBaseContext(), VidActivity.class);
    	    
    	    intent.putExtra("menuOption", menuOption);
            intent.putParcelableArrayListExtra("movieList",movieList);
     
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                    return false;
                }
     
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	if(currentVideoIndex < (movieList.size() - 1)){
    					currentVideoIndex = currentVideoIndex + 1;
    				}else{
    					currentVideoIndex = 0;
    				}
                intent.putExtra("listIndex", currentVideoIndex);
        		startActivity(intent);
        		VidActivity.this.overridePendingTransition(
    			R.anim.slide_in_right,
    			R.anim.slide_out_left
        		);
        		//android.os.Process.killProcess(android.os.Process.myPid());
        		finish();
        	    // right to left swipe
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	if(currentVideoIndex > 0){
                		currentVideoIndex = currentVideoIndex - 1;
    				}else{
    					currentVideoIndex = movieList.size() - 1;
    				}
                intent.putExtra("listIndex", currentVideoIndex);
        		startActivity(intent);
        		VidActivity.this.overridePendingTransition(
    			R.anim.slide_in_left, 
    			R.anim.slide_out_right
        		);
        		//android.os.Process.killProcess(android.os.Process.myPid());
        		finish();
                }
     
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {

            return super.onSingleTapConfirmed(e);
        }





        public boolean onTouch(View v, MotionEvent event) {

            // Within the MyGestureListener class you can now manage the event.getAction() codes.

            // Note that we are now calling the gesture Detectors onTouchEvent. And given we've set this class as the GestureDetectors listener 
            // the onFling, onSingleTap etc methods will be executed.
        	
        	return gDetector.onTouchEvent(event);
        }


        public GestureDetector getDetector()
        {
            return gDetector;
        }       
    }
}